package pers.weiney.controller;

import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import pers.weiney.pojo.Result;
import pers.weiney.pojo.User;
import pers.weiney.service.UserService;
import pers.weiney.utils.JwtUtil;
import pers.weiney.utils.Md5Util;
import pers.weiney.utils.ThreadLocalUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: @Weiney
 * @ClassName: UserController
 * @Description: 用户控制器
 * @Create: 2024-08-12
 **/
@RestController
@RequestMapping("/user")
@Validated // 使用spring validation来对参数进行验证：1.添加依赖 2. 参数前加注解 3. 类上加@Validated注解
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 查询用户是否已注册
        User user = userService.findByUserName(username);
        if (user == null) {
            // 用户为空，未占用，注册该用户
            userService.register(username, password);
            return Result.success();
        } else {
            // 被占用，注册失败
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        // 根据账号查询用户
        User loginUser = userService.findByUserName(username);
        // 验证用户是否存在
        if (loginUser == null) { // 用户不存在
            return Result.error("用户名错误");
        }
        // 验证密码是否正确（密码是密文）
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            // 登录成功
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            // 把token存储到redis中
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token, token, 1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        // 根据用户名获取用户信息
        // 用户名可从ThreadLocal中获取
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token){
        // 1. 校验参数
        String oldPwd = params.get("old_pwd"); // 旧密码
        String newPwd = params.get("new_pwd"); // 新密码
        String rePwd = params.get("re_pwd"); // 确认密码

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            // 三个参数有一个为空，则返回失败
            return Result.error("缺少必要参数");
        }

        if(!newPwd.equals(rePwd)){
            // 新密码和确认密码不一致
            return Result.error("新密码与确认密码不一致");
        }

        // 判断原密码是否正确，获取原密码
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);

        if(Md5Util.checkPassword(oldPwd, user.getPassword())){
            // 旧密码与数据库密码一致，修改密码
            userService.updatePwd(newPwd);
            // 删除redis中对应的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.getOperations().delete(token);

            return Result.success();
        } else {
            // 密码不一致
            return Result.error("原密码填写不正确");
        }
    }
}